//pickup.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js')

Page({
    data: {
        thdate:"",
        openid:"",
        // 提货最早可选时间
        validateStartDate:"",
        // 提货最晚可选时间
        validateEndDate:"",
        // 每个密码框最大限制长度
        pwdInputLen: 4,
        card:{
            cardNo:null,
            cardPwd:null
        },
        // 提货信息 BEGIN
        uname:"",
        tel:"",
        puaddress:"",
        detailaddress:"",
        tip:""
        // 提货信息 END
    },
    onLoad: function (options) {
        // 获取卡号和密码
        var param = JSON.parse(options.p);
        this.setData({
            card:{
                cardNo: param.cardNo,
                cardPwd: param.cardPwd
            }
        });

        var that = this;
        wx.cloud.callFunction({
            name: 'getOpenid',
            complete: res => {
                console.log('云函数获取到的openid: ', res.result.openid)
                var openid = res.result.openid;
                that.setData({
                    openid: openid
                })
            }
        })

        var dateNow = new Date();
        // 7天后日期
        var dateEnd = dateNow.getTime() + 60 * 60 * 1000 * 24 * 7;
        var dayTime = util.formatTime(dateNow);
        var onlyDate = dayTime.split(" ")[0].split("/");
        // 获取7天后的日期，作为可选日期
        var onlyDate2 = util.formatTime(new Date(dateEnd)).split(" ")[0].split("/");
        this.validateStartDate = onlyDate[0] + '-' + onlyDate[1] + '-' + onlyDate[2];
        this.validateEndDate = onlyDate2[0] + '-' + onlyDate2[1] + '-' + onlyDate2[2];
    },
    bindDateChange(e) {
        // 绑定发货日期
        this.setData({
            thdate: e.detail.value
        })
    },
    backtopcomfirm() {
        // 返回
        wx.navigateBack({
            delta: 0,
        })
    },
    bindinput_name(e) {
        this.setData({
            uname: e.detail.value
        })
    },
    bindinput_tel(e) {
        this.setData({
            tel: e.detail.value
        })
    },
    bindinput_address1(e) {
        this.setData({
            puaddress: e.detail.value
        })
    },
    bindinput_address2(e) {
        this.setData({
            detailaddress: e.detail.value
        })
    },
    bindinput_tip(e) {
        this.setData({
            tip: e.detail.value
        })
    },
    getUserInfo: function(e) {
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    submit() {
        // 订单号以时间开头
        // 8位时间 + SBDY + 8位随机
        var dateNow = new Date();
        var today = util.formatTime(dateNow);
        var reg = new RegExp("/",'g');
        var prefix = today.split(" ")[0].replace(reg,"");
        var randomStr = util.uuid();
        var OMS = prefix + randomStr.substring(0,4).toUpperCase();
        if(this.data.uname == null || this.data.uname == "") {
            wx.showToast({
                title: '收货人不能为空',
                icon: 'none',
                duration: 2000,
                mask: true
            })
            return;
        }
        if(this.data.tel == null || this.data.tel == "") {
            wx.showToast({
                title: '联系电话不能为空',
                icon: 'none',
                duration: 2000,
                mask: true
            })
            return;
        }
        if(this.data.thdate == null || this.data.thdate == "") {
            wx.showToast({
                title: '请选择收货日期',
                icon: 'none',
                duration: 2000,
                mask: true
            })
            return;
        }
        if(this.data.puaddress == null || this.data.puaddress == "") {
            wx.showToast({
                title: '收货地址不能为空',
                icon: 'none',
                duration: 2000,
                mask: true
            })
            return;
        }
        var truetime1 = util.formatTime(new Date()).split(" ")[0];
        // 戴老板需要这样，我不敢不从
        var reg = new RegExp("/",'g');
        var truetime = truetime1.replace(reg, "-");
        var item = {
            cardcode: this.data.card.cardNo,
            address: this.data.puaddress + this.data.detailaddress,
            orderid: OMS,
            receiver: this.data.uname,
            sjtime: "",
            status: 1,
            tel: this.data.tel,
            tip: this.data.tip,
            truetime: truetime,
            optime: new Date(),
            wlcode: "",
            yqtime: this.data.thdate
        }
        this.saveData(item);
        this.updateStatus(item);
    },
    // 保存数据
    saveData(item) {
        var that = this;
        const db = wx.cloud.database();
        db.collection("th_orders").add({
            data:item,
            success: res => {
                that.openSuccess({
                    thdate: item.yqtime,
                    OMS: item.orderid
                });
            },
            fail: err => {
                wx.showToast({
                  icon: 'none',
                  title: '预约失败，请联系管理员'
                })
                console.error('[数据库] [新增记录] 失败：', err)
            }
        })
    },
    updateStatus(item) {
        var _id = null;
        const db = wx.cloud.database();
        db.collection('th_cards').where({
            cardcode: item.cardcode
        }).get({
            success: function(res) {
                if(res.data.length != 0) {
                    _id = res.data[0]._id;

                    db.collection('th_cards').doc(_id).update({
                        data: {status: 0},
                        fail: err => {
                            wx.showToast({
                              icon: 'none',
                              title: '预约失败，请联系管理员'
                            })
                        }
                    })
                }  

            }
        })
        
    },
    openSuccess: function (item) {
        wx.redirectTo({
            url: 'psuccess/msg_success?p=' + JSON.stringify(item)
        })
    }

})
